package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 2020-11-26 09:26
 *
 * https://leetcode-cn.com/problems/remove-linked-list-elements/
 *
 */
public class _203_移除链表元素 {

    public ListNode removeElements(ListNode head, int val){

        if (head == null) {

            return null;
        }

        ListNode headNode = new ListNode(0);
        ListNode tailNode = headNode;
        headNode.next = head;

        while (tailNode.next != null) {

            if (tailNode.next.val == val) {


                tailNode.next = tailNode.next.next;
            }else {

                tailNode = tailNode.next;
            }

        }

        System.gc();
        return headNode.next;
    }
    /**
     * 使用头节点
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements02(ListNode head, int val) {

        if (head == null) {

            return null;
        }

        ListNode headNode = new ListNode(0);
        ListNode tailNode = headNode;

        while (head != null) {

            if (head.val != val) {

                tailNode.next = head;
                tailNode = head;
            }

            head = head.next;
        }
        System.gc();
        tailNode.next = null;
        return headNode.next;
    }
    /**
     * 没有使用头节点
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements01(ListNode head, int val) {

        if (head == null) {

            return null;
        }

        ListNode newHead = null,tail = null;

        while (head != null) {

            if (head.val != val) {

                if (newHead == null) {

                    newHead = head;
                }else {

                    tail.next = head;
                }
                tail = head;
            }

            head = head.next;
        }

        /**
         * 最后的tail next设置为 null
         */
        if (tail != null) {

            tail.next = null;
        }

        System.gc();

        return newHead;
    }
}
